<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        clearable
        placeholder="快递公司名称"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
      />
      <el-button
        v-waves
        style="margin-left: 10px"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleAdd"
      >
        新增
      </el-button>
      <el-upload
        class="filter-item"
        style="margin-left: 10px"
        :action="uploadExcelUrl"
        :headers="uploadExcelHeaders"
        :show-file-list="false"
        accept=".xlsx,.xls"
        :before-upload="beforeUploadExcel"
        :on-success="uploadExcelSuccess"
        :on-error="uploadExcelError"
      >
        <el-button size="small" type="success">上传快递公司列表Excel</el-button>
      </el-upload>
    </div>

    <el-table
      ref="itemDataTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top: 20px"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="ID"
        prop="id"
        align="center"
        width="80"
      />
      <el-table-column label="名称" align="center">
        <template slot-scope="{ row: { nameWrapper }}">
          <span v-html="nameWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="编码" align="center">
        <template slot-scope="{ row: { code }}">
          <span>{{ code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="{ row: { id } }">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(id)">编辑</el-button>
          <!-- <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="handleFilter"
    />

    <!-- 添加/编辑弹出框 -->
    <el-dialog
      :title="detailEditID !== 0 ? '编辑商店快递公司信息' : '添加商店快递公司信息'"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <shop-express-company-detail v-if="dialogFormVisible" :id="detailEditID" ref="shopExpressCompanyDetail" @ended="handleSubmitEnd" />
    </el-dialog>

  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import ShopExpressCompanyDetail from '../components/express-company/Detail'
import { getExpressCompanyList, deleteExpressCompany } from '@/api/shop-express-company'
import { wrapperKeyword } from '@/utils'
import { getToken } from '@/utils/auth'
import store from '@/store'

let uploadExcelLoading = null

export default {
  name: 'ShopExpressCompanyList',
  components: { Pagination, ShopExpressCompanyDetail },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      listLoading: false,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        name: ''
      },
      list: [],
      detailEditID: 0,
      dialogFormVisible: false,
      uploadExcelUrl: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API_PREFIX + 'shop_express_company/add_excel',
      uploadExcelHeaders: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  watch: {
    list(val) {
      val.forEach(express_company => {
        express_company.nameWrapper = wrapperKeyword(this.listQuery['name'] || '', express_company.name)
      })
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleFilter() {
      this.getList()
    },
    handleAdd() {
      this.detailEditID = 0
      this.dialogFormVisible = true
      this.$nextTick().then(() => {
        this.$refs.shopExpressCompanyDetail.getExpressCompanyByID()
      })
    },
    handleEdit(id) {
      this.detailEditID = id
      this.dialogFormVisible = true
      this.$nextTick().then(() => {
        this.$refs.shopExpressCompanyDetail.getExpressCompanyByID()
      })
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        // 判断是否为批量删除
        if (id === 0) {
          const _selection = this.$refs.itemDataTable.selection
          // console.log(_selection)
          if (_selection.length === 0) {
            this.$message({
              message: '请选择需要删除的数据',
              type: 'error'
            })
            return
          }
          _selection.forEach((value, index) => {
            ids.push(value.id)
          })
        } else {
          ids.push(id)
        }

        // console.log(ids)

        deleteExpressCompany(ids).then(response => {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.getList()
        })
      }).catch(() => {})
    },
    closeDialog() {
      this.$refs.shopExpressCompanyDetail.toDefault()
      this.detailEditID = 0
    },
    handleSubmitEnd() {
      this.dialogFormVisible = false
      this.getList()
    },
    getList() {
      this.listLoading = true
      getExpressCompanyList(this.listQuery).then(response => {
        const {
          total,
          data
        } = response
        this.total = total
        this.list = data
        this.listLoading = false
      })
    },
    beforeUploadExcel() {
      uploadExcelLoading = this.$loading({
        lock: true,
        text: '拼命解析Excel中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
    },
    uploadExcelSuccess(response) {
      // console.log(response)
      const { msg, errorCode } = response
      if (errorCode === 0) {
        this.$message({
          message: msg,
          type: 'success'
        })
        uploadExcelLoading.close()
        this.getList()
      }
    },
    uploadExcelError(err) {
      if (err) {
        // console.log(err, file, fileList)
        // console.log(err.message)
        uploadExcelLoading.close()
        const message = err.message ? JSON.parse(err.message) : { msg: '上传Excel失败', errorCode: 0 }
        this.$message({
          message: message.msg,
          type: 'error'
        })
        // err = JSON.stringify(err.message)
        if (message.errorCode === 30000 || message.errorCode === 30001) {
          // console.log('upload reset')
          // to re-login
          this.$confirm('Token 已失效，请重新登陆', '确认登出', {
            confirmButtonText: '重新登陆',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          }).catch(() => {})
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

